import FrameLog from "../../extensions/FrameLog"
import Singleton from "../design-pattern/Singleton"
import ViewLayer from "../view/ViewLayer"
import ViewPanel from "../view/ViewPanel"
import PoolMgr from "./PoolMgr"

export default class ViewMgr extends Singleton {
    private ViewList = Object.create({}) //面板显示列表
    private loadingView: { [key: string]: any } = {}
    /**
     * 打开面板
     * @param ViewName    面板名称
     * @param param     面板初始化参数
     * @param isCache   是否缓存面板
     */
    public openView(ViewClass: typeof ViewPanel, layerNode: cc.Node = ViewLayer.viewLayer, param?: any, callback?: () => void) {
        let url = ViewClass.getUrl()
        if (this.loadingView[url] || this.ViewList[url]) {
            FrameLog.warn("View加载中-->", this.loadingView[url] == null, " View已在显示列表-->", this.ViewList[url] == null, url)
            return
        }
        this.loadingView[url] = 1;
        PoolMgr.getInstance().get(url).then((temp) => {
            delete this.loadingView[url];
            this.showView(url, temp, layerNode, param)
            callback && callback()
        })
    }

    public closeView(ViewClass: typeof ViewPanel, destroy: boolean = false) {
        let temp = this.getView(ViewClass)
        let url = ViewClass.getUrl()
        if (temp) {
            let panel: ViewPanel = temp.getComponent(ViewPanel)
            if (panel) {
                panel.hide()
            }
            if (destroy) {
                temp.destroy()
            }
            else {
                PoolMgr.getInstance().put(url, temp)
            }
        }
        delete this.ViewList[url]
    }


    public getView(ViewClass: typeof ViewPanel): cc.Node {
        let url = ViewClass.getUrl()
        if (this.ViewList[url]) {
            return this.ViewList[url]
        }
        return null;
    }


    private showView(url: string, temp: cc.Node, layerNode: cc.Node, param: any = null) {
        temp.parent = layerNode;
        let panel: ViewPanel = temp.getComponent(ViewPanel)
        if (panel) {
            panel.show(param)
            panel.playIn()
        }
        this.ViewList[url] = temp;
    }

}